#include "JDir.h"
#include <boost/filesystem.hpp>
#include "JException.h"
#include <exception>

using namespace boost::filesystem;

JDir::JDir(void)
{

}


JDir::~JDir(void)
{
}

std::string JDir::RecurseUpFindFolder( std::string currentPath,std::string findDirName )
{
	//if(!is_directory(currentPath))
	//{
	//	if(path(currentPath).has_parent_path())
	//	{
	//		currentPath = path(currentPath).parent_path().string();
	//	}
	//}
	while(!HasDir(currentPath,findDirName))
	{
		path p(currentPath);
		if(p.has_parent_path())
		{
			currentPath = p.parent_path().string();
		}
		else
		{
			return std::string();
		}
	}
	return currentPath;
}

bool JDir::HasDir( std::string currentPath,std::string findDir )
{
	path p(currentPath);
	directory_iterator ite = directory_iterator(p);
	for(;ite != directory_iterator(); ++ite)
	{
		if(ite->path().filename() == findDir)
		{
			return true;
		}
	}
	return false;
}

bool JDir::IsExist( std::string fullDir )
{
	path p(fullDir);
	if(exists(p))
	{
		return true;
	}
	return false;
}

std::string JDir::CurrentWorkingPath()
{
	return current_path().string();
}

std::list<std::string> JDir::RecurseDownDir( std::string _rootPath )
{
	std::list<std::string> listFileName;
	if(is_directory(_rootPath) && exists(_rootPath))
	{
		DownDir(_rootPath,listFileName);
	}
	return listFileName;
}

void JDir::DownDir( std::string _rootPath,std::list<std::string>& listPath )
{
	listPath.push_back(_rootPath);
	if(is_directory(_rootPath))
	{
		directory_iterator ite = directory_iterator(_rootPath);
		for(;ite != directory_iterator(); ++ite)
		{
			DownDir(ite->path().string(),listPath);
		}
	}
}

void JDir::CreateDir( std::string _path )
{
	try
	{
		create_directory(_path);
	}
	catch(filesystem_error& e)
	{
		throw JFileException() << JErrorInfo(e.what());
	}
	catch(std::exception e)
	{
		throw JFileException() << JErrorInfo(e.what());
	}
}
